document.addEventListener('DOMContentLoaded', async () => {
  // 获取配置数据
  const { tools = [], useMenuBar = false } = await chrome.storage.local.get([
    'tools',
    'useMenuBar',
  ])

  // 渲染工具列表
  const toolList = document.querySelector('.tool-list')
  tools.forEach((tool) => {
    const item = document.createElement('div')
    item.className = 'tool-item'

    item.innerHTML = `
        <div class="tool-name"><img src="../icons/${tool.key}.png" />${
      tool.name
    }</div>
        <div class="tool-controls">
          <input 
            type="checkbox" 
            class="switch tool-check" 
            data-path="${tool.path}"
            ${tool.menuEnabled ? 'checked' : ''}
            ${useMenuBar ? '' : 'disabled'}
          >
        </div>
      `

    item.querySelector('.tool-name').addEventListener('click', () => {
      let url = tool.path
      if (tool.path.indexOf('http') < 0) {
        url = chrome.runtime.getURL(`apps/${tool.path}`)
      }
      chrome.tabs.create({
        url,
      })
    })

    toolList.appendChild(item)
  })

  // 全局菜单开关
  const globalToggle = document.getElementById('globalMenuToggle')
  globalToggle.checked = useMenuBar

  globalToggle.addEventListener('change', async (e) => {
    const useMenuBar = e.target.checked
    await chrome.storage.local.set({ useMenuBar })

    // 更新所有复选框状态
    document.querySelectorAll('.tool-check').forEach((checkbox) => {
      checkbox.disabled = !useMenuBar
    })

    // 切换点击功能
    document.querySelectorAll('.tool-name').forEach((name) => {
      name.style.cursor = useMenuBar ? 'default' : 'pointer'
    })
  })

  // 单个工具菜单配置
  document.querySelectorAll('.tool-check').forEach((checkbox) => {
    checkbox.addEventListener('change', async (e) => {
      const path = e.target.dataset.path
      const tools = (await chrome.storage.local.get('tools')).tools

      const updatedTools = tools.map((tool) =>
        tool.path === path ? { ...tool, menuEnabled: e.target.checked } : tool
      )

      await chrome.storage.local.set({ tools: updatedTools })
    })
  })
})
